<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" class="search-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item>
            <el-select 
              v-model="queryParams.inoutFlag" 
              placeholder="收支类型" 
              clearable 
              style="width: 100%"
            >
              <el-option
                v-for="(label, value) in BILL_INOUT_FLAG"
                :key="value"
                :label="label"
                :value="value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-select 
              v-model="queryParams.payPlatForm" 
              placeholder="支付方式" 
              clearable 
              style="width: 100%"
            >
              <el-option
                v-for="(label, value) in BILL_PAY_PLAT_FORM"
                :key="value"
                :label="label"
                :value="value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-input
              v-model="queryParams.searchStr"
              placeholder="请输入入住人/房源地址"
              clearable
              @keyup.enter="handleQuery"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              style="width: 100%"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleQuery">查 询</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 统计信息 -->
    <div class="flex-row-center mt20">
      <div>
        <span class="fs-base fc-secondary mr5">收入</span>
        <el-text type="success" size="large">￥{{ amountTotalInfo.incomeTotalMoney }}</el-text>
      </div>
      <div class="ml20">
        <span class="fs-base fc-secondary mr5">支出</span>
        <el-text type="danger" size="large">￥{{ amountTotalInfo.expensesTotalMoney }}</el-text>
      </div>
      <div style="flex: 1;"></div>
    </div>

    <!-- 表格区域 -->
    <el-table 
      :data="list" 
      v-loading="loading" 
      border
      style="margin-top: 20px"
    >
      <el-table-column label="费用名称" prop="name" min-width="120" />
      <el-table-column label="账单类型" prop="belong" min-width="100">
        <template #default="{ row }">
          {{ row.belong ? BILL_BELONG[row.belong] : "--" }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="renterName" min-width="100" />
      <el-table-column label="联系方式" prop="contacts" min-width="120" />
      <el-table-column label="地址" min-width="180">
        <template #default="{ row }">
          {{ row.room?.buildingName }}{{ row.room?.name }}
        </template>
      </el-table-column>
      <el-table-column label="分组" prop="room.groupName" min-width="120" />
      <el-table-column label="操作人" prop="receiverName" min-width="100" />
      <el-table-column label="支付方式" prop="payPlatForm" min-width="100">
        <template #default="{ row }">
          {{ row.payPlatForm ? BILL_PAY_PLAT_FORM[row.payPlatForm] : "--" }}
        </template>
      </el-table-column>
      <el-table-column label="金额" prop="money" min-width="120">
        <template #default="{ row }">
          <span :class="row.inoutFlag === '1' ? 'text-success' : 'text-danger'">
            {{ row.inoutFlag === "1" ? "+" : "-" }}{{ row.money.toFixed(2) }}元
          </span>
        </template>
      </el-table-column>
      <el-table-column label="日期" prop="payTime" min-width="160" />
      <el-table-column label="图片/备注" width="100">
        <template #default="{ row }">
          <el-space>
            <el-tooltip
              effect="dark"
              placement="top"
              v-if="row.remark"
            >
              <template #default>
                <el-icon class="fs-large" style="cursor: pointer;"><Tickets /></el-icon>
              </template>
              <template #content>
                <div style="max-width: 200px">{{ row.remark }}</div>
              </template>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="查看图片"
              placement="left"
              v-if="row.picUrl"
            >
              <template #default>
                <el-icon class="fs-large" style="cursor: pointer;"><Picture /></el-icon>
              </template>
              <template #content>
                <el-space>
                  <el-image 
                    v-for="(item, index) in JSON.parse(row.picUrl)" 
                    :key="index"
                    style="width: 150px;height: 150px;" 
                    :src="item.url" 
                    fit="contain" 
                  />
                </el-space>
              </template>
            </el-tooltip>
          </el-space>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-dropdown trigger="click" placement="bottom-start" @command="moreCommand($event, row)">
            <el-button link type="primary">更多</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="editImage">编辑图片</el-dropdown-item>
                <el-dropdown-item command="editRemark">编辑备注</el-dropdown-item>
                <el-dropdown-item command="remove">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-show="total > 0"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="val => { queryParams.pageSize = val; getList() }"
        @current-change="val => { queryParams.pageNum = val; getList() }"
      />
    </div>

    <!-- 编辑备注信息弹窗 -->
    <BillRemarkDl :visible="remarkVisible" :remark="currentBill.remark" @cancel="handleRemarkClose" @ok="handleRemarkOk"></BillRemarkDl>
    <!-- 编辑图片 -->
    <BillImageUploadDl :visible="imageVisible" :images="picUrlArray" @cancel="handleImageCancel" @ok="handleImageOk"></BillImageUploadDl>
    <!-- 预览图片 -->
    <el-dialog v-model="previewVisible">
      <img w-full :src="previewImageUrl" />
    </el-dialog>
    <!-- 删除账单弹窗 -->
    <BillRemoveDl :visible="removeBillingVisible" :info="currentBill" @cancel="handleRemoveBillingClose" @ok="handleRemoveBillingOk"></BillRemoveDl>
  </div>
</template>

<script setup name="Complete">
import SearchBar from '../component/searchBar.vue'
import { Picture, Tickets } from '@element-plus/icons-vue'
import billApi from '@/api/room/bill'
import useAppStore from '@/store/modules/app'
import useUserStore from '@/store/modules/user'
import BillImageUploadDl from '@/components/BillImageUploadDl/index.vue'
import BillRemarkDl from '@/components/BillRemarkDl/index.vue'
import BillRemoveDl from '@/components/BillRemoveDl/index.vue'
import { BILL_BELONG, BILL_INOUT_FLAG, BILL_PAY_PLAT_FORM } from '../constant'
import { parseTime, getWeekFirstDay, getWeekLastDay, getMonthFirstDay, getMonthLastDay } from '@/utils/ruoyi'

const { proxy } = getCurrentInstance()

const options = ref({
  group: true,
  type: true,
  inoutFlag: true,
  paymentType: true,
  searchStr: true,
  date: true
})
const remarkVisible = ref(false)
const imageVisible = ref(false)
const picUrlArray = ref([])
const previewVisible = ref(false)
const previewImageUrl = ref('')
const removeBillingVisible = ref(false)
const pictureUrlList = ref([])
const list = ref([])
const currentBill = ref({})
const loading = ref(false)
const total = ref(0)
const amountTotalInfo = ref({})
const fileList = ref([{
  name: 'food.jpeg',
  url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
}, {
  name: 'food.jpeg',
  url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
}])
const mobile = computed(() => useAppStore().device === 'mobile')
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  remarkForm: {
    remark: undefined
  },
  removeBillingForm: {
    id: undefined,
    buildingName: undefined,
    renterName: undefined,
    payDate: undefined,
    money: undefined
  },
})
const { queryParams, remarkForm, removeBillingForm } = toRefs(data)

const dateRange = ref([])

// 日期快捷选项
const dateShortcuts = [
  {
    text: '今日',
    value: () => {
      const today = new Date()
      return [today, today]
    }
  },
  {
    text: '昨日',
    value: () => {
      const yesterday = new Date()
      yesterday.setTime(yesterday.getTime() - 3600 * 1000 * 24)
      return [yesterday, yesterday]
    }
  },
  {
    text: '本周',
    value: () => {
      return [getWeekFirstDay(), getWeekLastDay()]
    }
  },
  {
    text: '上周',
    value: () => {
      const lastWeekFirstDay = new Date(getWeekFirstDay())
      lastWeekFirstDay.setTime(lastWeekFirstDay.getTime() - 3600 * 1000 * 24 * 7)
      const lastWeekLastDay = new Date(getWeekLastDay())
      lastWeekLastDay.setTime(lastWeekLastDay.getTime() - 3600 * 1000 * 24 * 7)
      return [lastWeekFirstDay, lastWeekLastDay]
    }
  },
  {
    text: '本月',
    value: () => {
      return [getMonthFirstDay(), getMonthLastDay()]
    }
  },
  {
    text: '上月',
    value: () => {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth()
      const lastMonthLastDay = new Date(year, month, 0)
      const lastMonthFirstDay = new Date(year, month - 1, 1)
      return [lastMonthFirstDay, lastMonthLastDay]
    }
  }
]

function handleDateChange(val) {
  if (val) {
    queryParams.value.beginTime = val[0]
    queryParams.value.endTime = val[1]
  } else {
    queryParams.value.beginTime = undefined
    queryParams.value.endTime = undefined
  }
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function getList() {
  loading.value = true
  billApi.getList({
    ...queryParams.value,
    status: '2',
  }).then(res => {
    list.value = res.data.rows
    total.value = res.data.total
    amountTotalInfo.value = res.data
  }).finally(() => {
    loading.value = false
  })
}

getList()

/* 搜索栏变化 */
function searchChange(form) {
  queryParams.value = { ...queryParams.value, ...form }
  getList()
}

// 更多操作按钮
function moreCommand(value, row) {
  currentBill.value = { ...row }
  switch (value) {
    case 'editImage':
      handleImage()
      break
    case 'editRemark':
      handleRemark()
      break
    case 'remove':
      handleRemoveBilling()
      break
    default:
      break;
  }
}

// 添加备注弹窗
function handleRemark() {
  remarkVisible.value = true
}
function handleRemarkClose() {
  remarkVisible.value = false
}
function handleRemarkOk(value) {
  // 判断表单值是否发生改变
  let params = {
    billId: currentBill.value.billId,
    ...value
  }
  billApi.update(params).then(() => {
    proxy.$modal.msgSuccess('备注修改成功')
    remarkVisible.value = false
    getList()
  })
  
}

// 编辑图片弹窗
function handleImage() {
  picUrlArray.value = currentBill.value.picUrl ? JSON.parse(currentBill.value.picUrl) : []
  imageVisible.value = true
}
function handleImageCancel() {
  imageVisible.value = false
}
function handleImageOk(value) {
  let params = {
    billId: currentBill.value.billId,
    picUrl: value
  }
  billApi.update(params).then(res => {
    proxy.$modal.msgSuccess('图片修改成功')
    imageVisible.value = false
    getList()
  })
}

// 删除账单
function handleRemoveBilling() {
  removeBillingVisible.value = true
}
function handleRemoveBillingClose() {
  removeBillingVisible.value = false
}
function handleRemoveBillingOk(billId) {
  billApi.remove(billId).then(() => {
    proxy.$modal.msgSuccess("账单删除成功");
    removeBillingVisible.value = false
    getList()
  })
}

// 添加重置方法
function handleReset() {
  // 重置日期为最近一周
  const end = new Date()
  const start = new Date()
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
  dateRange.value = [parseTime(start, '{y}-{m}-{d}'), parseTime(end, '{y}-{m}-{d}')]
  
  // 重置其他查询条件
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    beginTime: dateRange.value[0],
    endTime: dateRange.value[1]
  }
  
  // 执行查询
  getList()
}

// 在 onMounted 中设置默认日期范围
onMounted(() => {
  handleReset() // 初始化时设置为最近一周
})
</script>

<style lang="scss" scoped>
.text-success {
  color: var(--el-color-success);
}
.text-danger {
  color: var(--el-color-danger);
}
</style>
